<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="单据号" prop="nos">
        <el-input v-model="queryParams.nos" placeholder="请输入单据号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="订单编号" prop="projectNo">
        <el-input v-model="queryParams.projectNo" placeholder="请输入订单编号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="工程名称" prop="gongchengName">
        <el-input v-model="queryParams.gongchengName" placeholder="请输入工程名称"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品编码" prop="goodsCode">
        <el-input v-model="queryParams.goodsCode" placeholder="请输入产品编码"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品名称" prop="goodsName">
        <el-input v-model="queryParams.goodsName" placeholder="请输入产品名称"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品型号" prop="goodModel">
        <el-input v-model="queryParams.goodModel" placeholder="请输入产品型号"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="产品状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择产品状态" clearable >
          <el-option v-for="dict in dict.type.goods_status"
                     :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <!--<el-form-item label="是否自制" prop="isdo">
        <el-select v-model="queryParams.isdo" placeholder="是否自制" clearable style="width: 130px">
          <el-option v-for="dict in dict.type.isdo" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>-->
      <!--<el-form-item label="供应商" prop="supplierName">
          <el-input v-model="queryParams.supplierName" placeholder="请输入供应商名称"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>-->
      <el-form-item label="下单日期">
        <el-date-picker v-model="dateRange"
                        style="display: flex;"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="需求日期" prop="saleDate">
        <el-date-picker clearable v-model="queryParams.saleDate"
                        type="date" value-format="yyyy-MM-dd" placeholder="请选择需求日期">
        </el-date-picker>
      </el-form-item>
      <!--<el-form-item label="是否发货" prop="isfahuo">
          <el-input v-model="queryParams.isfahuo" placeholder="请输入是否发货"
                  clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="发货时间" prop="fahuoDate">
          <el-date-picker clearable v-model="queryParams.fahuoDate"
                          type="date" value-format="yyyy-MM-dd" placeholder="请选择发货时间">
          </el-date-picker>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="warning" plain icon="el-icon-download" size="mini"
                   @click="handleExport" >导出
        </el-button>
      </el-form-item>
    </el-form>

    <!--<el-row :gutter="10" class="mb8">
       <el-col :span="1.5">
           <el-popconfirm title="确认删除选择的数据项？" @confirm="handleDelete({})">
               <el-button slot="reference" type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                          v-hasPermi="['develop:GoodsSaledo:remove']">删除</el-button>
           </el-popconfirm>
       </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->
    <div v-if="selectedRows.length > 0">
      <span>已勾选请购数量合计: {{selectedRows.reduce((acc, row) => acc + row.orderCount, 0)}}</span>
    </div>
    <el-table border v-loading="loading" :data="dataList" @selection-change="handleSelectionChange" ref="table"
              :max-height="tableMaxHeight" @sort-change="handleSortChange"show-summary :summary-method="getSummaries">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column sortable label="单据号" align="center" prop="nos"/>
      <el-table-column sortable label="订单编号" align="center" prop="projectNo" show-overflow-tooltip />
      <el-table-column sortable label="工程名称" align="center" prop="gongchengName" />
      <el-table-column sortable label="客户名称" align="center" prop="customerName" />
      <el-table-column sortable label="产品编码" align="center" prop="goodsCode"/>
      <el-table-column sortable label="产品名称" align="center" prop="goodsName" show-overflow-tooltip/>
      <el-table-column sortable label="产品型号" align="center" prop="goodModel"/>
      <el-table-column sortable label="产品类型" align="center" prop="type" />
      <el-table-column label="订单数量" align="center" prop="orderCount"/>
      <el-table-column label="请购数量" align="center" prop="pleaseBuyCount"/>
      <el-table-column sortable label="中标价" align="center" prop="goodsTaxUnitPrice" />
      <el-table-column sortable label="下单日期" align="center" prop="ddDate" width="120">
        <template slot-scope="scope">
          <!-- <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
          <span>{{ parseTime(scope.row.ddDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="需求日期" align="center" prop="saleDate" width="120">
        <template slot-scope="scope">
         <!-- <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>-->
          <span>{{ parseTime(scope.row.saleDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column sortable label="是否自制" align="center" prop="isdo">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.isdo" :value="scope.row.isdo"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="产品状态" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.goods_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="操作"  align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- {{ showTrue +"和" +scope.row.status}} -->
          <el-button size="mini" type="text" icon="el-icon-info" v-show="scope.row.type == '产品' && (scope.row.status == '2' || scope.row.status == '1' ||
            scope.row.status == '11' || scope.row.status == '6' || scope.row.status == '38')"
                     v-hasPermi="['develop:GoodsSaleDo:kuguanxiugai']"  @click="elseHandleEdit(scope.row)">库管修改
          </el-button>
          <el-popconfirm :title="`确认退回产品吗？`" @confirm="handleSubmitToLvyue(scope.row)" v-show="( scope.row.status == '38' || scope.row.status == '2'|| scope.row.status == '1'
              || scope.row.status == '11' || scope.row.status == '6') && scope.row.type == '产品' "
                         v-hasPermi="['develop:GoodsSaleDo:kuguantuihui']"   style="margin-left: 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete">库管退回</el-button>
          </el-popconfirm>

          <el-button size="mini" type="text" icon="el-icon-info" v-hasPermi="['develop:GoodsSaleDo:jishuxiugai']"
                     v-show="scope.row.type == '产品' && (scope.row.status == '5' || scope.row.status == '3' ||  scope.row.status == '4' || scope.row.status == '39'
                     /*|| scope.row.status == '11' || scope.row.status == '6' */)" @click="handleEdit(scope.row)">技术修改
          </el-button>
          <el-popconfirm :title="`确认退回产品吗？`" @confirm="handleSubmitToKuguan(scope.row)"
                         v-show="( scope.row.status == '5' || scope.row.status =='3' || scope.row.status == '4' || scope.row.status == '39'
                         /*||  scope.row.status == '11' || scope.row.status == '6' */) && scope.row.type == '产品' " style="margin-left: 10px;">
            <el-button slot="reference" size="mini" type="text" icon="el-icon-delete" v-hasPermi="['develop:GoodsSaleDo:jishutuihui']" >技术退回</el-button>
          </el-popconfirm>
          <el-button @click="caigouDetail(scope.row)" icon="el-icon-view"  size="mini" type="text">
            采购记录
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList"/>
    <goodsSaledo-form ref="form" @ok="getList"></goodsSaledo-form>
    <edit-please-buy-form  ref="EditPleaseBuyFormList" @ok="getList" @close="editOpen = false" />
    <else-edit-please-buy-form  ref="ElseEditPleaseBuyFormList" @ok="getList" @close="editOpen = false" />
    <caigouDetail-form ref="caigouDetailForm" @ok="getList"></caigouDetail-form>
  </div>
</template>

<script>
import {deleteAction, downloadFile, getAction,updateAction ,accAdd} from '@/api/manage'
import GoodsSaledoForm from '@/views/develop/goodsSaledo/module/GoodsSaledoForm'
import { listQinggou } from "@/api/develop/goodsSaledo";
import EditPleaseBuyForm from '@/views/develop/pleaseBuy/module/editPleaseBuyFormList.vue'
import ElseEditPleaseBuyForm from '@/views/develop/pleaseBuy/module/elseEditPleaseBuyFormList.vue'
import CaigouDetailForm from '@/views/develop/pleaseBuy/module/CaigouDetailForm.vue'

export default {
  name: "PleaseBuyQinggouList",
  dicts: ['goods_status', 'isdo'],
  components: {
    GoodsSaledoForm,
    EditPleaseBuyForm,
    ElseEditPleaseBuyForm,
    CaigouDetailForm,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请购单（自制/采购/外协）表格数据
      dataList: [],
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        goodsId: null,
        goodsName: null,
        goodsBrand: null,
        goodModel: null,
        goodsUnitPrice: null,
        goodsCount: null,
        goodsTotalPrice: null,
        goodsBuyPrice: null,
        goodsBuyTotal: null,
        goodsProfit: null,
        saleDate: null,
        supplierId: null,
        supplierName: null,
        customerId: null,
        customerName: null,
        invoice: null,
        invoiceId: null,
        invoiceNo: null,
        fundCallback: null,
        receipt: null,
        saleId: null,
        saleName: null,
        projectId: null,
        projectNo: null,
        projectName: null,
        gongchengName: null,
        status: null,
        deptId: null,
        deptName: null,
        counts: null,
        shengyu: null,
        isfahuo: null,
        fahuoDate: null,
        huikuanDate: null,
        goodsCode: null,
        dun: null,
        nos: null,
        isdo: "0",
        mainId: null
      },
      url: {
        list: '/goodsSaledo/goodsSaledo/listQinggou',
        remove: '/goodsSaledo/goodsSaledo/',
        export: '/goodsSaledo/goodsSaledo/export',
      },
      selectedRows:[],
      tableMaxHeight: window.innerHeight - 320,
    };
  },
  created() {
    this.getList();
    window.addEventListener('resize', this.getTableHeight);
  },
  destroyed() {
    window.removeEventListener('resize', this.getTableHeight)
  },
  methods: {
    caigouDetail(row){
      this.$refs.caigouDetailForm.show(row);
    },
    handleSubmitToKuguan(row) {
      const data = row;
      data.status = '38';
      updateAction('/goodsSaledo/goodsSaledo/edit', data).then(response => {
        this.$modal.msgSuccess("退回成功");
        this.editOpen = false;
        this.getList();
        this.$emit('ok');
      });
    },
    handleSubmitToLvyue(row){
      updateAction('/goodsSaledo/goodsSaledo/editToLvyue', row).then(response => {
        this.$modal.msgSuccess("退回成功");
        this.editOpen = false;
        this.getList();
        this.$emit('ok');
      });
    },
    handleEdit(row) {
      this.$refs.EditPleaseBuyFormList.open(row);
    },
    elseHandleEdit(row) {
      this.$refs.ElseEditPleaseBuyFormList.opens(row);
    },
    getSummaries(param) {
      // console.log(param);
      const {columns, data} = param;
      const sums = [];

      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        // 只合计amount1和amount3，想合并哪些列就在这里指定
        if ( column.property === "orderCount" || column.property === "pleaseBuyCount") {

          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return accAdd(prev , curr);
            } else {
              return prev;
            }
          }, 0);
        }
      });
      return sums;
    },
             /** 排序触发事件 */
		handleSortChange(column, prop, order) {
		  this.queryParams.orderByColumn = column.prop;
		  this.queryParams.isAsc = column.order;
		  this.handleQuery();
		},
    /** 查询请购单（自制/采购/外协）列表 */
    getList() {
      this.loading = true;
      //getAction(this.url.list, this.queryParams).then(response => {
      listQinggou(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.dataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTableHeight() {
      this.tableHeight = window.innerHeight - 320
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.form.handleAdd();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.form.handleUpdate(row);
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      deleteAction(this.url.remove, ids).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      downloadFile(this.url.export, this.queryParams);
    },
  }
};
</script>
